<template>
  <view class="payment-container">
    <up-navbar bgColor="#1db0fc" autoBack leftIconColor="#fff" titleColor="#fff" placeholder />
    <!-- 收款人信息区域 -->
    <view class="recipient-section">
      <view class="recipient-header">
        <text class="recipient-title">{{ useT('付款给个人') }}</text>
      </view>
      <view class="recipient-info">
        <view class="recipient-details">
          <text class="recipient-name">{{ userInfo.nickname || useT('未知用户') }}</text>
          <text class="recipient-id" v-if="userInfo.phone">{{ useT('手机') }}: {{ maskPhone(userInfo.phone) }}</text>
          <text class="recipient-id" v-else>ID: {{ userInfo.uid || '' }}</text>
        </view>
        <view class="recipient-avatar">
          <image class="avatar-image" :src="userInfo.avatar || '/static/default-avatar.png'" mode="aspectFill" />
        </view>
      </view>
    </view>

    <!-- 付款详情区域 -->
    <view class="payment-details">
      <!-- 金额输入 -->
      <view class="amount-section">
        <text class="amount-label">{{ useT('金额') }}</text>
        <view class="amount-input-group">
          <text class="currency-symbol">T</text>
          <input class="amount-input" type="digit" :placeholder="useT('0.00')" v-model="paymentAmount" :placeholder-style="'color: #e9e9e9;'" @input="onAmountInput" />
        </view>
      </view>

      <!-- 备注输入 -->
      <view class="remark-section">
        <text class="remark-label">{{ useT('添加备注') }}</text>
        <input class="remark-input" type="text" :placeholder="useT('请输入备注信息')" :placeholder-style="'color: #e9e9e9;'" v-model="paymentRemark" maxlength="50" />
      </view>
    </view>

    <!-- 付款按钮 -->
    <view class="payment-button-area">
      <button class="payment-button" @click="submitPayment" :disabled="!canSubmit">
        <text class="payment-button-text">{{ isProcessing ? useT('付款中.') : useT('立即付款') }}</text>
      </button>
    </view>
  </view>
</template>

<script setup>
import { getUserBaseInfo, tradeMoney } from '@/api/user.js';
import { useT } from '@/utils/i18n.js';
import { onLoad } from '@dcloudio/uni-app';
import { computed, ref } from 'vue';

// 响应式数据
const userInfo = ref({
  nickname: '',
  uid: '',
  avatar: '',
  phone: ''
});

const paymentAmount = ref('');
const paymentRemark = ref('');
const recipientUserId = ref('');
const isProcessing = ref(false);

// 计算属性
const canSubmit = computed(() => {
  return paymentAmount.value && parseFloat(paymentAmount.value) > 0 && !isProcessing.value;
});

// 页面加载
onLoad((options) => {
  // 获取传递的收款人信息
  if (options.userId) {
    recipientUserId.value = options.userId;
    getUserInfo(options.userId);
  }
  if (options.amount) {
    paymentAmount.value = options.amount;
  }
});

// 获取收款人信息
const getUserInfo = async (userId) => {
  try {
    const response = await getUserBaseInfo({ uid: userId });
    console.log('收款人信息API响应:', response);

    // 检查响应状态
    if (response && response.data) {
      userInfo.value = {
        uid: response.data.uid,
        phone: response.data.phone,
        nickname: response.data.nickname,
        avatar: response.data.avatar
      };
      console.log('收款人信息:', userInfo.value);
    } else {
      throw new Error(response?.msg || useT('API响应格式错误'));
    }
  } catch (error) {
    console.error('获取收款人信息失败:', error);
    // 如果API调用失败，使用默认信息
    userInfo.value = {
      uid: userId,
      phone: '',
      nickname: useT('未知用户'),
      avatar: '/static/default-avatar.png'
    };
    uni.showToast({
      title: error?.message || useT('获取用户信息失败'),
      icon: 'none'
    });
  }
};

// 金额输入处理
const onAmountInput = (e) => {
  let value = e.detail.value;
  // 限制只能输入数字和小数点
  value = value.replace(/[^\d.]/g, '');
  // 限制只能有一个小数点
  const parts = value.split('.');
  if (parts.length > 2) {
    value = `${parts[0]}.${parts.slice(1).join('')}`;
  }
  // 限制小数点后两位
  if (parts.length === 2 && parts[1].length > 2) {
    value = `${parts[0]}.${parts[1].substring(0, 2)}`;
  }
  paymentAmount.value = value;
};

// 提交付款
const submitPayment = () => {
  if (!canSubmit.value) {
    uni.showToast({
      title: useT('请输入有效金额'),
      icon: 'none'
    });
    return;
  }

  const amount = parseFloat(paymentAmount.value);
  if (amount <= 0) {
    uni.showToast({
      title: useT('金额必须大于0'),
      icon: 'none'
    });
    return;
  }

  // 检查收款人信息
  if (!recipientUserId.value) {
    uni.showToast({
      title: useT('收款人信息错误'),
      icon: 'none'
    });
    return;
  }

  // 显示确认弹窗
  uni.showModal({
    title: useT('确认付款'),
    content: `${useT('确认向')} ${userInfo.value.nickname} ${useT('付款')} T${paymentAmount.value}？`,
    cancelText: useT('取消'),
    confirmText: useT('确认'),
    success: (res) => {
      if (res.confirm) {
        processPayment();
      }
    }
  });
};

// 处理付款
const processPayment = async () => {
  // 防止重复提交
  if (isProcessing.value) {
    return;
  }

  isProcessing.value = true;
  uni.showLoading({
    title: useT('付款中.')
  });

  try {
    // 调用真实的付款API
    const response = await tradeMoney({
      number: paymentAmount.value,
      to_uid: recipientUserId.value,
      mark: paymentRemark.value
    });

    uni.hideLoading();

    // 检查响应状态
    if (response && response.status === 200) {
      uni.showToast({
        title: useT('付款成功'),
        icon: 'success'
      });

      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      throw new Error(response?.msg || useT('付款失败'));
    }
  } catch (error) {
    uni.hideLoading();
    console.error('付款失败:', error);

    // 显示错误信息
    uni.showToast({
      title: error || useT('付款失败，请重试'),
      icon: 'none',
      duration: 2000
    });
  } finally {
    isProcessing.value = false;
  }
};

// 手机号脱敏处理
const maskPhone = (phone) => {
  if (!phone || phone.length !== 11) {
    return phone;
  }
  // 显示前3位和后4位，中间用****代替
  return `${phone.substring(0, 3)}****${phone.substring(7)}`;
};
</script>

<style lang="scss" scoped>
.payment-container {
  min-height: 100vh;
  background: #1db0fc;
  padding: 0;
}

.recipient-section {
  background: rgba(255, 255, 255, 0.2);
  padding: 40rpx 30rpx;
  margin-bottom: 20rpx;
}

.recipient-header {
  margin-bottom: 30rpx;
}

.recipient-title {
  color: #ffffff;
  font-size: 36rpx;
  font-weight: 600;
}

.recipient-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.recipient-details {
  flex: 1;
}

.recipient-name {
  display: block;
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.recipient-id {
  display: block;
  color: rgba(255, 255, 255, 0.7);
  font-size: 26rpx;
}

.recipient-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-left: 20rpx;
}

.avatar-image {
  width: 100%;
  height: 100%;
}

.payment-details {
  background: rgba(255, 255, 255, 0.2);
  padding: 40rpx 30rpx;
}

.amount-section {
  margin-bottom: 40rpx;
}

.amount-label {
  display: block;
  color: #ffffff;
  font-size: 28rpx;
  margin-bottom: 20rpx;
}

.amount-input-group {
  display: flex;
  align-items: center;
  border-bottom: 2rpx solid rgba(255, 255, 255, 0.3);
  padding-bottom: 20rpx;
}

.currency-symbol {
  color: #ffffff;
  font-size: 48rpx;
  font-weight: 600;
  margin-right: 20rpx;
}

.amount-input {
  flex: 1;
  color: #ffffff;
  font-size: 48rpx;
  font-weight: 600;
  background: transparent;
  border: none;

  &::placeholder {
    color: rgba(255, 255, 255, 0.3);
  }
}

.remark-section {
  margin-bottom: 20rpx;
}

.remark-label {
  display: block;
  color: #ffffff;
  font-size: 28rpx;
  margin-bottom: 20rpx;
}

.remark-input {
  width: 100%;
  color: #ffffff;
  font-size: 28rpx;
  background: transparent;
  border: none;
  border-bottom: 2rpx solid rgba(255, 255, 255, 0.3);

  &::placeholder {
    color: rgba(255, 255, 255, 0.3);
  }
}

.payment-button-area {
  position: fixed;
  bottom: 40rpx;
  left: 30rpx;
  right: 30rpx;
}

.payment-button {
  width: 100%;
  height: 100rpx;
  background: #ffffff;
  border: none;
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);

  &:disabled {
    background: rgba(255, 255, 255, 0.3);
    box-shadow: none;
  }
}

.payment-button-text {
  color: #3875ea;
  font-size: 32rpx;
  font-weight: 600;
}
</style>
